#!/usr/bin/env python
import os
import argparse


PROJECT_APP_PY = """#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os.path
ROOT = os.path.abspath(os.path.dirname(__file__))
from july import JulyApplication, run_server

#: define a demo handler for you
#: delete it as your wish
from tornado.web import RequestHandler


class HomeHandler(RequestHandler):
    def get(self):
        self.write('hello july project')


handlers = [
    ('/', HomeHandler),
]


settings = dict(
    cookie_secret='secret',
    xsrf_cookies='secret',
    login_url='/account/login',

    template_path=os.path.join(ROOT, 'templates'),
    static_path=os.path.join(ROOT, 'static'),
    static_url_prefix='/static/',
)

application = JulyApplication(handlers=handlers, debug=True, **settings)

#: you can add a handler later
#: application = JulyApplication(debug=True)
#: application.add_handler(('/', HomeHandler))

#: register an app
#: from myapp.handlers import myapp
#: application.register_app(myapp, url_prefix='/app')

if __name__ == '__main__':
    run_server(application)
"""


APP_HANDLERS_PY = """# -*- coding: utf-8 -*-
from july import JulyHandler, JulyApp


class HomeHandler(JulyHandler):
    #: if you don't want to load template from in app
    #: app_template = False

    def get(self):
        self.write('hello july app')

        #: render from in app template
        #: self.render('myapp/home.html')


handlers = [
    ('/', HomeHandler),
]

myapp = JulyApp('myapp', __name__, handlers=handlers,
                template_folder="templates")

#: you can add handler later by
#: myapp.add_handler(('/', HomeHandler))
"""


def startproject(name):
    """Project structure::

        name/
            __init__.py
            app.py
            static/
            templates/
    """
    os.makedirs('%s/static' % name)
    os.makedirs('%s/templates' % name)

    f = open('%s/__init__.py' % name, 'w')
    f.write('')
    f.close()

    f = open('%s/app.py' % name, 'w')
    f.write(PROJECT_APP_PY)
    f.close()


def startapp(name):
    """App structure::

        name/
            __init__.py
            handlers.py
            templates/
    """
    os.makedirs('%s/templates' % name)

    f = open('%s/__init__.py' % name, 'w')
    f.write('')
    f.close()

    f = open('%s/handlers.py' % name, 'w')
    f.write(APP_HANDLERS_PY)
    f.close()


def main():
    parser = argparse.ArgumentParser(
        prog='july',
        description=('July is a better way to organize your tornado project')
    )
    parser.add_argument('command', nargs='*')

    args = parser.parse_args()
    if args.command:
        command = args.command[0]
    else:
        command = None

    if command == 'startproject':
        startproject(args.command[1])
    elif command == 'startapp':
        startapp(args.command[1])


if __name__ == '__main__':
    main()
